package cn.kailangtu.serialutils.api;

import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.SystemClock;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.util.List;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

public class SerialPortApiUSB {

    private Context context;
    private static String TAG = "SerialPortApi==>";
    private String portName;
    private int baudrate;
    private int flags;
    private LinkedBlockingQueue<String> reportMsgQueue = null;
    private LinkedBlockingQueue<String> sendMsgQueue = null;
    private LinkedBlockingQueue<String> sourceMsgQueue = null;
    private static boolean isProcess = false;
    private static boolean isSending = false;
    private static boolean isSpying = false;
    private static boolean isProcessMsg = false;
    private ReceiveLogMessageListenerV2 logMsgListne = null;

    private long lastReceiveTime =0;


    private static SerialPortApiUSB instance = null;

    private  byte[] rxByteArray;
    private  int resultSize;

    private SerialPortApiUSB(){

    }


    public static SerialPortApiUSB getInstance() {
        if(instance ==null)
        {
            instance = new SerialPortApiUSB();
        }
        return instance;
    }

    public void Init(Application context,ReceiveLogMessageListenerV2 logListner){

        this.context = context;
        this.logMsgListne = logListner;
    }




    UsbSerialPort port;
    public boolean openSerialPortV2(String portName,int baudrate,int flags){
        int count = 0;
        this.baudrate = baudrate;
        openUsb();

       return true;

    }

    long sendCount,receiveCount;

    private boolean openUsb()
    {
        try {
            // Find all available drivers from attached devices.
            UsbManager manager = (UsbManager) this.context.getSystemService(Context.USB_SERVICE);
            List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
            if (availableDrivers.isEmpty()) {
                return false;
            }


            // Open a connection to the first available driver.
            UsbSerialDriver driver = availableDrivers.get(0);


            //WCHUARTManager.getInstance().requestPermission(context, driver.getDevice());
            //SystemClock.sleep(200);

            Intent intent = new Intent("com.exmple.USB_PERMISSION");//发送自定义广播
            PendingIntent pendingIntent =
                    PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, 0);
            manager.requestPermission(driver.getDevice(),pendingIntent);
            SystemClock.sleep(200);

            // Open a connection to the first available driver.
            UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
            if (connection == null) {
                // add UsbManager.requestPermission(driver.getDevice(), ..) handling here
                return false;
            }

            port = driver.getPorts().get(0); // Most devices have just one port (port 0)
            port.open(connection);
            port.setParameters(256000, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            SerialInputOutputManager serialInputOutputManager =   new SerialInputOutputManager(port, new SerialInputOutputManager.Listener() {
                @Override
                public void onNewData(byte[] data) {


                    //这里处理收到的数据


                }

                @Override
                public void onRunError(Exception e) {

                }
            });

            serialInputOutputManager.start();
            return true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }




    public void close(){
        try {
            port.close();
        }
        catch(Exception e)
        {

        }
    }





    public void addSendString(String data){
        try {
            sendMsgQueue.offer(data);
            //port.write(CommonUtils.hexStringToByteArray(data), 100);
        }
        catch(Exception e)
        {

        }

    }





    public long getLastReceiveTime(){
        return lastReceiveTime;
    }

    public void setLastReceiveTime(long lastReceiveTime)
    {
        this.lastReceiveTime = lastReceiveTime;
    }



    long lastSendTime2 = 0;
    long lastReceiveTime2 = 0;







    public static void sendKeyboardEvent(int keyCode)
    {
        try{
            String keyCommand = "input keyevent "+keyCode;
            Runtime.getRuntime().exec(keyCommand);
            Log.e("KEYBOARD",keyCommand);
        }
        catch(Exception e)
        {
            Log.e("KEYBOARD",e.getMessage());
            e.printStackTrace();
        }
    }



    public void showMsg(String message){
        if(logMsgListne != null)
        {
            logMsgListne.onLogMessage(message);
        }
    }

    boolean isSpy = false;



    public void closeSpy(){
        isSpy = false;
    }
}
